const { Service } = require("uni-cloud-router");
const { result_success, result_error } = require('http-result-modle');
const { checkToken } = require('common-uni-id');
const db = uniCloud.database();

module.exports = class ShopieService extends (
    Service
) {

    async addShopie(event) {
        let params;
        if(event.params){
            params = event.params;
        }else if(event.data){
            params = event.data;
        }else{
            return result_error('参数丢失', null);
        }

        if(!params){
            return result_error('参数丢失', null);
        }
        if(!params.app_id){
            return result_error('应用id参数不能为空', null);
        }
        if(!params.shop_id){
            return result_error('门店id参数不能为空', null);
        }
        if(!params.order_no){
            return result_error('订单编号参数不能为空', null);
        }
        if(!params.title){
            return result_error('收支标题参数不能为空', null);
        }
        if(!params.cate){
            return result_error('收支类别参数不能为空', null);
        }
        if(!params.type){
            return result_error('收支类型参数不能为空', null);
        }
        if(!params.way){
            return result_error('收支方式参数不能为空', null);
        }
        if('' === params.money || null === params.money || undefined === params.money || 0 === parseFloat(params.money)){
            return result_error('收支金额参数不能为空', null);
        }

        let userInfo = null;
        if (this.ctx.event.uniIdToken) {
            const userRes = await checkToken(this.ctx.event.uniIdToken);

            if(userRes.userInfo){
                userInfo = userRes.userInfo;
            }
        }
        if (!userInfo) {
            return result_error('当前用户未登录', null);
        }

        let shopie = {
            app_id: params.app_id,
            shop_id: params.shop_id,
            order_no: params.order_no,
            title: params.title,
            cate: params.cate,
            type: params.type,
            way: params.way,
            money: params.money,
            creator_id: userInfo._id ? userInfo._id : null,
            creator_name: userInfo.username ? userInfo.username : null,
            create_time: new Date().getTime(),
            full_id: null,
            full_name: null
        };

        let addShopieResult = await db.collection('wmzmall-gathering-order').add(shopie);
        if(!addShopieResult || !addShopieResult.id){
            return result_error('新增收支记录数据失败', null);
        }

        return result_success(addShopieResult.id, '新增收支记录数据成功');
    }

    async cloudAddShopie(appId, shopId, orderNo, title, cate, type, way, money) {
        return await this.addShopie({
            data: {
                app_id: appId,
                shop_id: shopId,
                order_no: orderNo,
                title: title,
                cate: cate,
                type: type,
                way: way,
                money: money
            }
        });
    }

};
